package controller;

import com.google.gson.Gson;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import pojo.Blog;
import pojo.Image;
import service.ImageService;
import utils.FileUpload;
import utils.util;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/image")
public class ImageController {

    @Resource
    private ImageService imageService;

    @RequestMapping("/uploadImage")
    private String uploadImage(HttpServletRequest request) throws Exception {
        FileUpload.springUpload(request);
        return "success";

    }

    @RequestMapping("/addImage")
    public String addImage(@RequestParam Map<String, String> map) throws NoSuchAlgorithmException {
        String strImg = map.get("strImg");//获取安卓端传过来的键
        Gson gson = new Gson();
        Image image = gson.fromJson(strImg, Image.class);
        int i = imageService.insert(image);
        if (i > 0) {
            // String JsonStr = new Gson().toJson(blog);
            //return JsonStr;
            return "success";
        } else {
            return "fail";     //保存失败
        }
    }

    @RequestMapping("/getImageMap")
    public void getImageMap(@RequestParam Map<String, String> map, HttpServletResponse response) {
        String userid = map.get("userid");
        List<Image> list = imageService.getImageMap(userid);
        System.out.println("aaaaaaa");
        System.out.println("aa" + list);
        String JsonStr = new Gson().toJson(list);
        try {
            response.setContentType("charset=UTF-8");
            response.getWriter().write(JsonStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @CrossOrigin
    @RequestMapping("getImageCount")
    public String getImageCount() {
        int imageNums = imageService.getImageCount();
        String JsonStr = new Gson().toJson(imageNums);
        return JsonStr;

    }

    @CrossOrigin
    @RequestMapping("getallImageMap")
    public void getallImageMap(HttpServletResponse response) {
        List<Image> list = imageService.getallImageMap();
        String JsonStr = new Gson().toJson(list);
        try {
            response.setContentType("charset=UTF-8");
            response.getWriter().write(JsonStr);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    @CrossOrigin
    @RequestMapping("/deleteImagebyname")
    public void deleteImagebyname(String id) {
        System.out.println(id);
        imageService.deleteImagebyname(id);
    }
}

